<template>
  <!-- 模板部分保持不变 -->
  <view>
    <scroll-view scroll-y="true" class="scroll-wrapper">
      <view>
        <view class="wrap">
          <u-form ref="uForm" :rules="rules" :model="model" :errorType="errorType">

            <!-- 所在地区 -->
            <u-form-item
                required
                label-width="150"
                :border-bottom="false"
                prop="villageCity"
                label="所在地区"
            >
              <div @click="showPicker()" style="margin-right: 30rpx;">选择</div>
              <u-input
                  v-model="model.villageCity"
              />
            </u-form-item>

            <u-form-item :label-position="labelPosition" label="小区名称" prop="villageName" label-width="180"
                         :leftIconStyle="{color:'#d5d5d5'}">
              <u-input :border="border" type="text" :select-open="selectShow" v-model="model.villageName"
                       placeholder="请选择小区(必选)"></u-input>
            </u-form-item>


            <!-- left-icon="file-text" -->
            <u-form-item :label-position="labelPosition" label="详细地址" prop="address" label-width="180"
                         :leftIconStyle="{color:'#d5d5d5'}" right-icon="map"
                         :rightIconStyle="{color:'#d5d5d5'}">
              <div @click="clickUniMap()" style="margin-right: 30rpx;">地图选择</div>
              <u-input :border="border" placeholder="请优先地图选择详细地址" v-model="model.address" type="text"
                      ></u-input>
            </u-form-item>

            <u-form-item label-width="150" :label-position="labelPosition" label="房屋面积" required>
              <u-input :border="border" placeholder="请输入房屋面积" v-model="model.roomArea"
                       type="number"></u-input>
            </u-form-item>
            <u-form-item label-width="150" :label-position="labelPosition" label="期望租金" required>
              <u-input :border="border" placeholder="请输入租金" v-model="model.price" type="number"></u-input>
            </u-form-item>

            <!--            rentalList  出租方式-->
            <u-form-item :label-position="labelPosition" label="出租方式" label-width="180">
              <u-input :border="border" type="select" :select-open="rentalShow" v-model="typeVo"
                       placeholder="请选择朝向" @click="rentalShow = true"></u-input>
            </u-form-item>


            <view class="custom-gap"></view>
            <u-form-item :label-position="labelPosition" label="房源图片" label-width="150" required>
              <u-upload
                  :custom-btn="true" ref="uUpload" :auto-upload="true" :action="action" :file-list="fileList"
                  :max-size="10 * 1024 * 1024" max-count="9" width="160" height="160"
                  :size-type="siteType">
                <view slot="addBtn" class="slot-btn" hover-class="slot-btn__hover" hover-stay-time="150">
                  <u-icon name="plus" size="60" :color="$u.color['lightColor']"></u-icon>
                </view>
              </u-upload>
            </u-form-item>


            <!--            add-->

            <!--            <u-form-item  :label-position="labelPosition" label="房牌号" prop="houseNo" label-width="180"-->
            <!--                          left-icon="home" :leftIconStyle="{color:'#d5d5d5'}">-->
            <!--              <u-input :border="border" placeholder="请输入门牌号(必填)" v-model="model.houseNo" type="text"></u-input>-->
            <!--            </u-form-item>-->
            <!--            <u-form-item  :label-position="labelPosition" label="装修" prop="decoration" label-width="180" left-icon="eye" :leftIconStyle="{color:'#d5d5d5'}">-->
            <!--              <u-input :border="border" type="select" placeholder="请选择装修(必选)":select-open="decorationShow" v-model="model.decoration"  @click="decorationShow = true"></u-input>-->
            <!--            </u-form-item>-->
            <u-form-item :label-position="labelPosition" label="房东姓名" prop="ownerName" label-width="180"
                         :leftIconStyle="{color:'#d5d5d5'}">
              <u-input :border="border" placeholder="请输入房东姓名(必填)" v-model="model.ownerName"
                       type="text"></u-input>
            </u-form-item>
            <u-form-item :label-position="labelPosition" label="联系方式" prop="owerPhone" label-width="180"
                         :leftIconStyle="{color:'#d5d5d5'}">
              <u-input :border="border" placeholder="请输入联系方式(必填)" v-model="model.owerPhone"
                       type="number" maxlength="11"></u-input>
            </u-form-item>

            <u-form-item label-width="150" :label-position="labelPosition" label="起租日期">
              <view class="dateBtn" @click="dateClick">
                {{dateLabel}}<u-icon name="arrow-right"></u-icon>
              </view>
            </u-form-item>

            <u-form-item label-width="150" :label-position="labelPosition" label="房源亮点" required>
              <u-checkbox-group @change="checkboxGroupChange" :width="radioCheckWidth"
                                :wrap="radioCheckWrap">
                <u-checkbox v-model="item.checked" v-for="(item, index) in checkboxList" :key="index"
                            :name="item.name">{{ item.name }}</u-checkbox>
              </u-checkbox-group>
            </u-form-item>

            <u-form-item label-width="150" :label-position="labelPosition" label="房源描述">
              <u-input type="textarea" :border="border" placeholder="请填写房屋描述"
                       v-model="model.introduce"/>
            </u-form-item>



          </u-form>
        </view>
      </view>
    </scroll-view>
    <u-select mode="single-column" :list="selectList" v-model="selectShow" @confirm="selectConfirm"></u-select>
    <u-select mode="single-column" :list="directionList" v-model="directionShow" @confirm="directionConfirm"></u-select>
    <u-action-sheet :list="actionSheetList" v-model="actionSheetShow" @click="actionSheetCallback"></u-action-sheet>
    <u-calendar v-model="show" :mode="mode" @change="changeDate" max-date="2100-01-01"></u-calendar>

    <!--    出租方式-->
    <u-select mode="single-column" :list="rentalList" v-model="rentalShow" @confirm="rentalConfirm"></u-select>

    <m-city
        :provinceData="list"
        headTitle="区域选择"
        ref="cityPicker"
        @funcValue="getPickerParentValue"
        pickerSize="4"
    >
    </m-city>


    <view class="bottom-btn">
      <u-button type="primary" @click="submit">提交</u-button>
    </view>

    <uniMap v-if="mapFlag" @close="closeMap" @callback="callBackAddress" />


  </view>
</template>

<script>
import {saveHouse, updateHouse,findHouseById} from "@/api/house.js";
import uniMap from "@/components/uniMap";
import city from "@/components/m-city/m-city.vue";
import { upload } from "@/api/common.js";

import permision from "@/js_sdk/wa-permission/permission.js";
//import config from "@/config/config.js" // 全局配置文件
export default {
  components: {
    "m-city": city,
    uniMap,
  },
  // props: {
  //   model: Object
  // },
  data() {
    return {
      villageName: "",
      address: "",
      mapFlag: false,
      villageCity: "",
      model: {
        address: "",
        houseNo: "",
        decoration: "",
        ownerName: "",
        owerPhone: "",

      },
      addressTemp: "",
      fileList: [],
      list: [
        {
          id: "",
          localName: "请选择",
          children: [],
        },
      ],
      isButtonDisabled: false,
      timer: null,
      roomLabelVo: '',
      directionVo: '',
      show: false,
      mode: 'date',
      selectList: [
        {
          value: '1',
          label: '主卧'
        },
        {
          value: '2',
          label: '次卧'
        }
      ],
      rentalList: [
        {
          value: '0',
          label: '整租'
        },
        {
          value: '1',
          label: '合租'
        },
        {
          value: '2',
          label: '短租'
        }
      ],
      directionList: [
        {
          value: '东',
          label: '东'
        },
        {
          value: '南',
          label: '南'
        },
        {
          value: '西',
          label: '西'
        },
        {
          value: '北',
          label: '北'
        },
      ],
      border: false,
      check: false,
      checkboxList: [
        {
          name: '看房方便',
          checked: false,
          disabled: false
        },
        {
          name: '独卫',
          checked: false,
          disabled: false
        },
        {
          name: '独立阳台',
          checked: false,
          disabled: false
        }

      ],
      actionSheetList: [
        {
          text: '电梯房'
        },
        {
          text: '楼梯房'
        }
      ],
      selectShow: false,
      directionShow: false,
      rentalShow: false,
      radioCheckWidth: 'auto',
      radioCheckWrap: false,
      labelPosition: 'left',
      errorType: ['toast'],
      actionSheetShow: false,
      storeAddressIdPath: "",
      dateLabel: '随时入住',
      typeVo: '',
      // 图片服务器地址
      action: upload,
      siteType: ['compressed'],
      rules: {
        villageCity: [{ required: true, message: '请选择所在地区' }],
        villageName: [{ required: true, message: '请选择小区名称' }],
        address: [{ required: true, message: '请选择详细地址' }],
        roomArea: [{ required: true, message: '请输入房屋面积' }],
        price: [{ required: true, message: '请输入期望租金' }],
        type: [{ required: true, message: '请选择出租方式' }],
        ownerName: [{ required: true, message: '请输入房东姓名' }],
        owerPhone: [{ required: true, message: '请输入联系方式' }],
        startDate: [{ required: true, message: '请选择起租日期' }],
        featureList: [{ required: true, message: '请选择至少一个房源亮点' }],
        introduce: [{ required: true, message: '请填写房源描述' }]
      }
    };
  },
  watch: {
    model: {
      handler(newName, oldName) {
        if (!this.model) {
          this.model = {};
        }
        // typeVo
        if (this.model.type == 0) {
          this.typeVo = '整租'
        } else if (this.model.type == 1) {
          this.type = '合租'
        } else if (this.model.type == 2) {
          this.type = '短租'
        } else if (this.model.type == 10) {
          this.type = '新房'
        }
        // this.address=this.model.address
        // this.villageName=this.model.villageName
        // 回显房源亮点
        if (this.model.featureList) {
          this.checkboxList.forEach(item => {
            this.model.featureList.forEach(feature => {
              if (feature.feature == item.name) {
                item.checked = true
              }
            })
          })

        }
      },
      immediate: true,
      deep: true
    }
  },
  onShow(option) {
    if(option.houseId!=undefined  && null!=option.houseId){

      findHouseById({
        id:option.houseId
      }).then(res=>{
        this.model = res.data.data
      })
    }
  },
  onReady() {
     this.$refs.uForm.setRules(this.rules);
  },
  methods: {
    // 关闭地图
    closeMap() {
      this.mapFlag = false;
    },
    // 打开地图并访问权限
    clickUniMap() {
      // #ifdef APP-PLUS
      if (plus.os.name == "iOS") {
        // ios系统
        permision.judgeIosPermission("location")
            ? (this.mapFlag = true)
            : this.refuseMap();
      } else {
        // 安卓
        this.requestAndroidPermission(
            "android.permission.ACCESS_FINE_LOCATION"
        );
      }
      // #endif

      // #ifndef APP-PLUS
      this.mapFlag = true;
      // #endif
    },

    // 如果拒绝权限 提示区设置
    refuseMap() {
      uni.showModal({
        title: "温馨提示",
        content: "您已拒绝定位,请开启",
        confirmText: "去设置",
        success(res) {
          if (res.confirm) {
            //打开授权设置
            // #ifndef MP-WEIXIN
            uni.getSystemInfo({
              success(res) {
                if (res.platform == "ios") {
                  //IOS
                  plus.runtime.openURL("app-settings://");
                } else if (res.platform == "android") {
                  //安卓
                  let main = plus.android.runtimeMainActivity();
                  let Intent = plus.android.importClass(
                      "android.content.Intent"
                  );
                  let mIntent = new Intent("android.settings.ACTION_SETTINGS");
                  main.startActivity(mIntent);
                }
              },
            });
            // #endif
          }
        },
      });
    },

    // 获取安卓是否拥有地址权限
    async requestAndroidPermission(permisionID) {
      var result = await permision.requestAndroidPermission(permisionID);

      if (result == 1) {
        this.mapFlag = true;
      } else {
        this.refuseMap();
      }
    },

    // 选择地址后数据的回调
    callBackAddress(val) {
      console.log(val)
      uni.showLoading({
        title: "加载中",
      });
      console.info("选择地址后数据的回调"+val)
      if (val.regeocode && val) {
        let address = val.regeocode;
       //val.regeocode.addressComponent.district
        this.model.address=address.formatted_address
      //  console.info(address+ this.address);
        this.model.villageName= val.name;
       // console.info("villageName====="+ this.villageName);
         this.model.villageCity=address.addressComponent.province+address.addressComponent.city+address.addressComponent.district
        //console.info("villageCity====="+this.villageCity);
        // this.form.detail = address.formatted_address; //地址详情
        // this.form.___path = val.data.result.name;
        // this.form.consigneeAddressIdPath = val.data.result.id; // 地址id分割
        // this.form.consigneeAddressPath = val.data.result.name; //地址名称， '，'分割
         this.model.latitude = val.latitude; //纬度
         this.model.longitude = val.longitude; //经度
        uni.hideLoading();
      }

      this.mapFlag = !this.mapFlag; //关闭地图
    },
    getPickerParentValue(e) {
      // 检查 model 是否为空，若为空则初始化
      if (!this.model) {
        this.model = {};
      }
      this.model.storeAddressIdPath = [];
      console.log(e)
      let name = "";
      e.forEach((item, index) => {
        if (item.id) {
          // 遍历数据
          this.model.storeAddressIdPath.push(item.id);
          if (index == e.length - 1) {
            name += item.localName;
          } else {
            name += item.localName + ",";
          }
          this.villageCity = name
          this.$set(this.model, 'villageCity', name)
        }
      });

      // this.form.storeCenter = e[e.length-1].center
    },
    // 显示三级地址联动
    showPicker() {
      this.$refs.cityPicker.show();
    },
    submit() {
      if (this.isButtonDisabled) return;



      let files = [];
      // 通过filter，筛选出上传进度为100的文件(因为某些上传失败的文件，进度值不为100，这个是可选的操作)
      files = this.$refs.uUpload.lists.filter(val => {
        return val.progress == 100;
      })
      if (this.$u.test.isEmpty(files)) {
        //return this.$mytip.toast('请至少选择一张房源图片')
      }
      let imageList = files.map(val => {
        if (undefined != val.response) {
          return {
            imageName: val.response.realName,
            imagePath: val.response.fileName,
            imgUrl: val.response.url,
            imageSize: val.file.size
          }
        } else {
          var foundVo = this.model.imageList.find(vo => vo.imgUrl === val.url);
          return {
            imageName: foundVo.imageName == null ? null : foundVo.imageName,
            imagePath: foundVo.imagePath == null ? null : foundVo.imagePath,
            imgUrl: foundVo.imageUrl == null ? null : foundVo.imageUrl,
            imageSize: foundVo.imageSize == null ? null : foundVo.imageSize
          }
        }
      })
      this.model.imageList = imageList
      // if (this.$u.test.isEmpty(this.model.featureList)) {
      //   uni.showToast({
      //     title: "请至少选择一个房源亮点",
      //   });
      //   return
      //
      // }

      // this.model.address=this.address
      // this.model.villageName=this.villageName
      // this.model.villageCity=this.villageCity


      this.$refs.uForm.validate((valid) => {
        if (valid) {
          if (this.model.id) {

            updateHouse(this.model).then((result) => {

              this.isButtonDisabled = true;

              // 设置定时器，5秒后重新启用按钮
              this.timer = setTimeout(() => {
                this.isButtonDisabled = false;
              }, 5000);


              this.$u.route({
                url: 'pages/house/order',
              })
            });


          } else {

            saveHouse(this.model).then((result) => {

              if (result.data.code == 200) {
                this.isButtonDisabled = true;

                // 设置定时器，5秒后重新启用按钮
                this.timer = setTimeout(() => {
                  this.isButtonDisabled = false;
                }, 5000);


                this.$u.route({
                  url: 'pages/house/order',
                })
              } else {
                uni.showToast({
                  title: result.data.msg,
                });
              }

            });

          }
        }else{
        }
      });






    },
    // 选择类型回调
    selectConfirm(e) {
      this.model.roomLabel = ''
      this.model.roomType = ''
      e.map((val, index) => {
        this.model.roomLabel += val.label;
        this.model.roomType += val.value;
      })
      this.roomLabelVo = this.model.roomLabel
    },
    directionConfirm(e) {
      e.map((val, index) => {
        this.model.direction = val.label;
        this.directionVo = val.label;
      })
    },
    rentalConfirm(e) {

      e.map((val, index) => {
        this.model.type = val.value;
        this.typeVo = val.label;
      })
    },


    // 点击actionSheet回调
    actionSheetCallback(index) {
      uni.hideKeyboard();
      this.model.stepType = this.actionSheetList[index].text;
    },
    // checkbox选择发生变化
    checkboxGroupChange(e) {
      let featureList = e.map(val => {
        return {
          feature: val
        }
      })
      this.model.featureList = featureList
    },
    borderChange(index) {
      this.border = !index;
    },
    labelPositionChange(index) {
      this.labelPosition = index == 0 ? 'left' : 'top';
    },
    codeChange(text) {
      this.codeTips = text;
    },
    dateClick() {
      this.show = true
    },
    changeDate(e) {
      this.model.startDate = e.result
      this.dateLabel = e.result
    }
  }
};
</script>

<style>
page {
  background-color: #FFFFFF;
}
</style>
<style scoped lang="scss">

.wrap {
  padding: 30rpx;
}

.scroll-wrapper {
  position: absolute;
  left: 0rpx;
  right: 0rpx;
  top: 0rpx;
  bottom: 120rpx;
}

.bottom-btn {
  position: fixed;
  bottom: 8rpx;
  width: 100%;
  padding: 30rpx;
  border-top: 1rpx solid #ccc;
  background-color: #FFFFFF;
}

.dateBtn {
  position: absolute;
  right: 0rpx;
  top: 10rpx;
  color: #606266;
}

.slot-btn {
  width: 160rpx;
  height: 160rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgb(244, 245, 246);
  border-radius: 10rpx;
}

.slot-btn__hover {
  background-color: rgb(235, 236, 238);
}

.custom-gap {
  width: 1000rpx;
  height: 10rpx;
  margin: 0 -200rpx 0 -200rpx;
  background-color: rgb(235, 236, 238);
}
</style>